package org.utnrepasa.net;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Esta clase espera solicitudes del cliente y crea un hilo por cada una de
 * ellas. Ésta se usa del lado del servidor.
 *
 * @author Parisi Germán
 * @version 1.0
 */
public class Server {

    public static final int PORT = 9003;
    private static Server me;
    private final List<Connection> connections;
    private boolean listening;

    private Server() {
        this.connections = new ArrayList<Connection>();
        this.listening = true;
    }

    public static Server getInstancia() {
        if (me == null) {
            me = new Server();
        }
        return me;
    }

    public void waitAndAccept() {
        try {
            ServerSocket ss = new ServerSocket(PORT);
            while (this.listening) {
                Socket socket = ss.accept();
                Connection con = new Connection(socket);
                this.connections.add(con);
                Thread th = new Thread(con);
                th.start();
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public boolean isListening() {
        return this.listening;
    }

    public List<Connection> getConnections() {
        return this.connections;
    }

    public void setListening(boolean listening) {
        this.listening = listening;
    }

}
